<?php

namespace App\Http\Controllers\Api\V1;

use App\Enums\ResponseCode;
use App\Http\Controllers\Api\AbstractApiController;
use App\Models\CompanyModel;
use App\Models\JobpositionModel;
use App\Models\User;
use App\Services\Easemob\EasemobService;
use App\Services\Im\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WechatImController extends AbstractApiController
{

    protected $request;
    protected $wechat_service;

    public function __construct(Request $request, WechatService $service)
    {
        $this->request = $request;
        $this->wechat_service = $service;
    }


    public function get_token()
    {
        $input = $this->request->validate([
            'user_id' => 'required|',
        ]);
        return $this->success(trans("success"), ResponseCode::OK, [
            'UserSig' => $this->wechat_service->get_token($input['user_id'])
        ]);
    }

    public function test()
    {
        // $user = auth('api')->user();

        $input = $this->request->validate([
            'type' => 'required|',
        ]);

        if ($input['type'] == 1) {
            $model = new User();
            $list = $model->where('is_im', 0)->get();
            $fix = 'user_';
        } elseif ($input['type'] == 2) {
            $model = new CompanyModel();
            $list = $model->where('is_im', 0)->get();
            $fix = 'company_';
        } elseif ($input['type'] == 3) {
            $model = new JobpositionModel();
            $list = $model->where('is_im', 0)->get();
            $fix = 'job_position_';
        } else {
            $list = [];
        }

        foreach ($list as &$u) {
            $wechatIm = new WechatService;
            // $u->defaultAvatar();
            if ($input['type'] == 1) {
                $im = $this->wechat_service->create($fix . $u->id, $u->name, $u->defaultAvatar());
                $wechatIm->attribute('user_' . $u->id, empty($u->name) ? 'user' . $u->id : $u->name,   $u->defaultAvatar());
                if ($im->ActionStatus == 'OK') {
                    $u->update(['is_im' => 1]);
                }
            }

            if ($input['type'] == 3) {
                $im = $this->wechat_service->create($fix . $u->id, $u->name, $u->uploads);
                $wechatIm = new WechatService;
                $company = CompanyModel::where('id', $u->company_id)->first();
                $name = empty($company->contact_person_name) ? $company->company_name : $company->contact_person_name;
                $head = empty($company->contact_person_avatar) ? $company->logoUrl() : $company->contact_person_avatar;

                $content = $u->position_name . $u->salary  . '/' . JobpositionModel::SALARY_TYPE_LIST[$u->salary_type];
                $wechatIm->attribute('job_' . $u->id,  $name,  $head, $content);

                if ($im->ActionStatus == 'OK') {
                    $u->update(['is_im' => 1]);
                }
            }
        }
        // $service->test()
        $a = [];
        return $this->success(trans("success"), ResponseCode::OK, $a);
    }

    /**
     * 获取单个用户的详细信息
     * $username  用户名
     */
    public function get_userinfo(EasemobService $EasemobService)
    {
        $user = auth('api')->user();
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->get($user->uuname));
    }

    /**
     * 添加好友
     * $username  要添加好友的用户名
     * $contact   好友用户名
     */
    public function addfriend(Request $request, EasemobService $EasemobService)
    {
        $user = auth('api')->user();
        $input = $request->validate([
            'contact' => 'required|',
        ]);
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->add($user->uuname, $input["contact"]));
    }

    /**
     * 好友列表
     * $username  要获取好友列表的用户名
     *  
     */
    public function get_friendlist(EasemobService $EasemobService)
    {
        $user = auth('api')->user();
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->get_friendlist($user->uuname));
    }

    //获取环信token
    public function hxtoken(EasemobService $EasemobService)
    {
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->hxtoken());
    }

    //获取用户token
    public function usertoken(Request $request, EasemobService $EasemobService)
    {
        $input = $request->validate([
            'username' => 'required',
        ]);
        $username = $input["username"];
        //$username = "shop_uuid_10";
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->usertoken($username));
    }

    /**
     * 设置用户属性
     * $username  要设置属性的用户名
     * $contact   要设置的属性（键：属性名；值：属性值）
     */
    public function attribute(Request $request, EasemobService $EasemobService)
    {
        $user = auth('api')->user();
        $input = $request->validate([
            'nickname' => 'required',
        ]);
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->attribute("user_uuid_130", $input));
    }

    /**
     * 获取用户属性
     * $username  用户名
     * 
     */
    public function getMetadataFromUser(Request $request, EasemobService $EasemobService)
    {
        $user = auth('api')->user();
        return $this->success(trans("success"), ResponseCode::OK, $EasemobService->getMetadataFromUser("shop_uuid_10"));
    }


    //获取会话列表用户信息  from发送者   to接收者
    public function getconversation_list(Request $request)
    {
        // $input = $request->validate([
        //     "conversation_data"=>'required|array',
        // ]);
        //$conversation_data = $input["conversation_data"];
        $conversation_data = [
            [
                'from' => 'user_uuid_130',
                'to' => "shop_uuid_9_23",
                'msg' => '怒火',
                'timestamp' => '1728543191995',
                'type' => 'img',
            ],
            // [
            //     'from' => 'user_uuid_130',
            //     'to' => "shop_uuid_23",
            //     'msg' => '你好',
            //     'timestamp' => '1728543191995',
            //     'type' => 'txt',
            // ]
        ];
        $newto = [];
        foreach ($conversation_data as $key => $val) {
            $from = explode("_", $val["from"]);
            $to = explode("_", $val["to"]);
            if ($from[0] == "user") {
                $user = DB::table("user")->where("uuname", $val["from"])->first();
                $userfrom = [
                    "avatar_url" => $user->avatar_url,
                    "name" => $user->name,
                ];
                $company_hx = DB::table("company_hx")->where("uuname", $val["to"])->first();
                $company = DB::table("company")->where("id", $company_hx->company_id)->first();
                $position = DB::table("sign_up_job_position")->where("user_id", $from[2])->where("uuname", $val["to"])->first();
            } elseif ($from[0] == "shop") {

                $user = DB::table("user")->where("uuname", $val["to"])->first();
                $userfrom = [
                    "avatar_url" => $user->avatar_url,
                    "name" => $user->name,
                ];
                $company_hx = DB::table("company_hx")->where("uuname", $val["from"])->first();
                $company = DB::table("company")->where("id", $company_hx->company_id)->first();
                //  $company = DB::table("company")->where("uuname",$val["from"])->first();
                $position = DB::table("sign_up_job_position")->where("user_id", $to[2])->where("uuname", $val["from"])->first();
            }
            if (!empty($company->contact_person_avatar)) {
                $contact_person_avatar = $company->contact_person_avatar;
            } else {
                $contact_person_avatar = CompanyModel::DEFAULT_CONTACT_PERSON;
            }

            $arr = [
                "user_id" => $user->id,
                "company_id" => $company->id,
                "contact_person_name" => $company->contact_person_name,
                "contact_person_avatar" => $contact_person_avatar,
                "position_name" => $position->position_name,
                "salary" => $position->salary,
                "salary_type" => $position->salary_type,
                "job_position_id" => $position->job_position_id,
                "timestamp" => date('m-d H:i', $val["timestamp"] / 1000),
                "type" => $val["type"],
                "msg" => $val["msg"],
                "to" => $val["to"],
                "from" => $val["from"],
                // "unReadcount"=>$val["unReadcount"],
            ];
            array_push($newto, $arr);
        }
        $res = [
            "from" => $userfrom,
            "newto" => $newto
        ];
        return $this->success(trans("success"), ResponseCode::OK, $res);
    }

    //会话绑定职位
    public function conversation_bind_position(Request $request)
    {
        $input = $request->validate([
            'to' => 'required',
            'position_id' => 'required',
        ]);
        $user = auth('api')->user();
        $res = DB::table("sign_up_job_position")->where("user_id", $user->id)->where("job_position_id", $input["position_id"])->first();
        if (empty($res->uuname)) {
            DB::table("sign_up_job_position")->where("user_id", $user->id)->where("job_position_id", $input["position_id"])->update(["uuname" => $input["to"]]);
        }
        return $this->success(trans("success"), ResponseCode::OK);
    }

    //插入环信聊天记录
    public function add_hxchat_history(Request $request)
    {
        //is_type  1用户发送  2招聘者发送
        $input = $request->validate([
            'type' => 'required',
            'msg' => 'required',
            'to' => 'required',
            'from' => 'required',
            'is_type' => 'required',
            "msgid" => "required"
        ]);
        if ($input["is_type"] == 2) {
            $user = DB::table("user")->where("uuname", $input["to"])->first();
            $company = DB::table("company")->where("uuname", $input["from"])->first();
            $input["user_id"] = $user["id"];
            $input["company_id"] = $company["id"];
        }
        $input["created_at"] = date("Y-m-d H:i:s", time());
        DB::table("hxchat_history")->insert($input);
        return $this->success(trans("success"), ResponseCode::OK);
    }
}
